<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $user_id
 * @property string $user_name
 * @property string $nick_name
 * @property string $url
 * @property string $password
 * @property string $email_address
 * @property string $school_name
 * @property string $register_date
 * @property string $last_login_date
 * @property string $last_login_ip
 * @property integer $status
 *
 * The followings are the available model relations:
 * @property TblCourse[] $tblCourses
 * @property TblCourseTeacher[] $tblCourseTeachers
 * @property TblLab[] $tblLabs
 * @property TblNews[] $tblNews
 * @property TblResources[] $tblResources
 * @property TblTeaching[] $tblTeachings
 */
class User extends CActiveRecord
{
	public $oldpassword;
	public $oldpasswordrep;
	public $password_repeat;
	public $verifyCode;
	public $role;

    const STATUS_ACTIVE = 1;
    const STATUS_DEACTIVE = 0;

    public function getUserStatus()
    {
        return array (
            self::STATUS_ACTIVE => 'ACITVE',
            self::STATUS_DEACTIVE => 'DEACTIVE',
        );
    }
    public function isSameUser($uid)
	{
		return $this->user_id === $uid;
	}
	public function isActive()
	{
		return $this->status == self::STATUS_ACTIVE;
	}


    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_user';
	}
    public function getRoleText()
    {
        $auth=Yii::app()->authManager;
        if($auth->checkAccess('root', $this->user_id))
        {
            return "超级管理员";
        }
        elseif($auth->checkAccess('admin', $this->user_id))
        {
            return '管理员';
        }
        else
        {
            return '普通用户';
        }
    }
	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_name, nick_name, password, password_repeat, email_address, tel, job_number, college, school_name, verifyCode', 'required'),
			array('user_name', 'match', 'pattern'=>'/^[\w\d]+$/','message'=>'Only characters and digits should used in user name'),
            array('password_repeat', 'compare', 'compareAttribute'=>'password','on'=>'register,update'),
            array('oldpassword, oldpasswordrep','compareOldPassword','on'=>'update'),
			array('oldpassword', 'required','on'=>'update'),
			array('email_address', 'email'),
			array('user_name, email_address', 'unique'),
			array('status', 'numerical', 'integerOnly'=>true),
			array('user_name, nick_name, password, last_login_ip, tel, job_number', 'length', 'max'=>20),
			array('url', 'length', 'max'=>200),
			array('email_address', 'length', 'max'=>80),
			array('school_name, college', 'length', 'max'=>100),
			array('last_login_date', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('user_id, user_name, nick_name, url, password, email_address, school_name, register_date, last_login_date, last_login_ip, status, tel, job_number, college, role', 'safe', 'on'=>'search'),
			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
		);
	}
    public function checkAccess($param)
    {
        $model = AuthAssignment::model()->find("itemname = '{$param}' and userid = ".$this->user_id);
        if($model == null)
        {
            return false;
        }
            return true;
    }
    public function compareOldPassword($attribute,$params)
    {
        if($this->oldpassword != $this->oldpasswordrep)
        {
            $this->addError('oldpassword','旧密码错误！');
        }
    }
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'tblCourses' => array(self::HAS_MANY, 'TblCourse', 'user_id'),
			'tblCourseTeachers' => array(self::HAS_MANY, 'TblCourseTeacher', 'user_id'),
			'tblLabs' => array(self::HAS_MANY, 'TblLab', 'user_id'),
			'tblNews' => array(self::HAS_MANY, 'TblNews', 'user_id'),
			'tblResources' => array(self::HAS_MANY, 'TblResources', 'user_id'),
			'tblTeachings' => array(self::HAS_MANY, 'TblTeaching', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
        return array(
			'user_id' => yii::t("models/User",'ID'),
			'user_name' => yii::t("models/User",'UserName'),
			'nick_name' => yii::t("models/User",'NickName'),
			'url' => yii::t("models/User",'Url'),
			'password' => yii::t("models/User",'Password'),
			'email_address' => yii::t("models/User",'Email Address'),
			'school_name' => yii::t("models/User",'School Name'),
			'register_date' => yii::t("models/User",'Register Date'),
			'last_login_date' => yii::t("models/User",'Last Login Date'),
			'last_login_ip' => yii::t("models/User",'Last Login Ip'),
			'status' => yii::t("models/User",'Status'),
			'password_repeat' => yii::t("models/User",'Password Repeat'),
            'tel' => '联系电话',
            'job_number' => '学号/工号',
            'college' => '学院',
            'oldpassword' => '旧密码',
            'oldpasswordrep' => '旧密码',
            'role'=>'角色',
		);
	}
    
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.
		$criteria=new CDbCriteria;

		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('user_name',$this->user_name,true);
		$criteria->compare('nick_name',$this->nick_name,true);
		$criteria->compare('url',$this->url,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('email_address',$this->email_address,true);
		$criteria->compare('school_name',$this->school_name,true);
		$criteria->compare('tel',$this->tel,true);
		$criteria->compare('job_number',$this->job_number,true);
		$criteria->compare('college',$this->college,true);
		$criteria->compare('register_date',$this->register_date,true);
		$criteria->compare('last_login_date',$this->last_login_date,true);
		$criteria->compare('last_login_ip',$this->last_login_ip,true);
		$criteria->compare('status',$this->status);
		$criteria->order = 'user_id DESC';

        if($this->role == 1)
        {
            $Assignment = AuthAssignment::model()->findAll("itemname = 'admin' or itemname = 'root'");
            foreach($Assignment as $elem)
            {
                $strlist[] = $elem->userid;
            }
            $strlist = implode(',',$strlist) == "" ? "-1" : implode(',',$strlist);
            $criteria->addCondition('user_id not in ('.$strlist.')');
        }
        elseif($this->role == 2)
        {
            $Assignment = AuthAssignment::model()->findAll("itemname = 'admin' and itemname != 'root'");
            foreach($Assignment as $elem)
            {
                $strlist[] = $elem->userid;
            }
            $strlist = implode(',',$strlist) == "" ? "-1" : implode(',',$strlist);
            $criteria->addCondition('user_id in ('.$strlist.')');
        }
	    elseif($this->role == 3)
        {
            $Assignment = AuthAssignment::model()->findAll("itemname = 'root'");
            foreach($Assignment as $elem)
            {
                $strlist[] = $elem->userid;
            }
            $strlist = implode(',',$strlist) == "" ? "-1" : implode(',',$strlist);
            $criteria->addCondition('user_id in ('.$strlist.')');
        }
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
    }
	/**
	 * Override the method beforeSave.
	 * If the $this is a new record, then before save it to database,
	 * assign the 'NOW()' the the 'last_login_date' column.
	 * @author : xgqin <xgqin@guet.edu.cn>
	 * @copy date : 13/05/2014
	 */
	public function beforeSave()
	{
		if ($this->isNewRecord)
		{
			$this->last_login_date = new CDbExpression('NOW()');
		}
		return parent::beforeSave();
	}

}
